//
//  LoDeContentViewController.m
//  Wallets Manager
//
//  Created by MAC on 10/31/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "LoDeContentViewController.h"

@interface LoDeContentViewController ()


@end

@implementation LoDeContentViewController
@synthesize loandebtTableView;
@synthesize popUpViewHistory;
@synthesize popUpViewHistoryFinished;
@synthesize currentDate;
@synthesize startDate,endDate;
@synthesize isCategoryMode;
@synthesize loanTotal;
@synthesize debtTotal;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Get Income and Expense Array
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDate:currentDate];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDate:currentDate];
    debtRowNumber = [debtArray count];
    
    loanCompletedArray = [[NSMutableArray alloc] init];
    debtCompletedArray = [[NSMutableArray alloc] init];
    
    [self reloadLoanDebtHistory];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLoan_OnSuccess :) name:@"addLoan_OnSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addDebt_OnSuccess :) name:@"addDebt_OnSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLoanDebtHistory_onSuccess : ) name:@"addLoanDebtHistory_onSuccess" object:nil];
}

- (void)viewDidUnload
{
    [self setLoandebtTableView:nil];
    [self setPopUpViewHistory:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table View Delegate

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(!isCategoryMode) {
        return  [loanArray count]+[debtArray count];
    } else {
        if(section == 0) {
            return [loanArray count];
        } else {
            return [debtArray count];
        }
    }
    
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    if(!isCategoryMode){
        return  1;
    } else {
        return 2;
    }
    
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,320,30)];
    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sub_navbar_bg.png"]];
    //-------------------Format Date Section --------------------//
    
    
    UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 200, 20)];
    if(!isCategoryMode) {
        sectionTitleLabel.text = @"Loan & Debt Diary";
    } else {
        if(section == 0) {
            sectionTitleLabel.text = @"Loan Diary";
        }else {
            sectionTitleLabel.text = @"Debt Diary";
        }
    }
    
    
    
    sectionTitleLabel.textColor = [UIColor whiteColor];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14];
    sectionTitleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:sectionTitleLabel];
    
    return headerView;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellInditifier = @"CellInditifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInditifier] ;
    
    UIImageView *imageView;
    UILabel *titleLabel;
    UITextField *amountTextField;
    UITextField *completedTextField;
    UILabel *dayLabel;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    
    if( cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInditifier];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 40, 40)];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 100;
        [cell addSubview:imageView];
        
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 200, 20)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor colorWithRed:99.0/255.0 green:182.0/255.0 blue:67.0/255.0 alpha:1];
        titleLabel.tag = 200;
        [cell addSubview:titleLabel];
        
        amountTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 10, 280, 20)];
        amountTextField.textColor = [UIColor whiteColor];
        amountTextField.backgroundColor = [UIColor clearColor];
        amountTextField.font = [UIFont systemFontOfSize:12];
        amountTextField.tag = 300;
        amountTextField.enabled = NO;
        [cell addSubview:amountTextField];
        
        completedTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, 280, 20)];
        completedTextField.textColor = [UIColor whiteColor];
        completedTextField.backgroundColor = [UIColor clearColor];
        completedTextField.font = [UIFont systemFontOfSize:12];
        completedTextField.tag = 400;
        completedTextField.enabled = NO;
        [cell addSubview:completedTextField];
        
        dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 35, 200, 10)];
        dayLabel.backgroundColor = [UIColor clearColor];
        dayLabel.textColor = [UIColor blackColor];
        dayLabel.tag = 500;
        dayLabel.font = [UIFont italicSystemFontOfSize:12.0f];
        [cell addSubview:dayLabel];
    }
    
    imageView               = (UIImageView*)[cell viewWithTag:100];
    titleLabel              = (UILabel*)    [cell viewWithTag:200];
    amountTextField         = (UITextField*)[cell viewWithTag:300];
    completedTextField      = (UITextField*)[cell viewWithTag:400];
    dayLabel                = (UILabel*)    [cell viewWithTag:500];

    if(!isCategoryMode) {
        if( indexPath.row < [loanArray count]) {
            Loan *tempLoan = [loanArray objectAtIndex:indexPath.row];
            titleLabel.text = tempLoan.l_name;
            if (tempLoan.l_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-money.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempLoan.l_amount floatValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
            
            completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[loanCompletedArray objectAtIndex:indexPath.row] doubleValue]];
            
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempLoan.l_date];
        } else {
            Debt *tempDebt = [debtArray objectAtIndex:indexPath.row - [loanArray count]];
            titleLabel.text = tempDebt.d_name;
            if (tempDebt.d_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-save.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempDebt.d_amount floatValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
            completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[debtCompletedArray objectAtIndex:indexPath.row - [loanArray count]] doubleValue]];
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempDebt.d_date];
        }
        
    } else {
        if(indexPath.section == 0) {
            Loan *tempLoan = [loanArray objectAtIndex:indexPath.row];

            titleLabel.text = tempLoan.l_name;
            if (tempLoan.l_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-money.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempLoan.l_amount doubleValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];

            completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[loanCompletedArray objectAtIndex:indexPath.row] doubleValue]];
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempLoan.l_date];
        } else {
            Debt *tempDebt = [debtArray objectAtIndex:indexPath.row];
            titleLabel.text = tempDebt.d_name;
            if (tempDebt.d_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-save.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempDebt.d_amount doubleValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
            completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[debtCompletedArray objectAtIndex:indexPath.row] doubleValue]];
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempDebt.d_date];
        }
    }
    
    CGSize amountTextFieldSize = [amountTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    amountTextField.frame = CGRectMake(290-amountTextFieldSize.width,5 , amountTextFieldSize.width+15, 20);
    
    CGSize completedTextFieldSize = [completedTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    completedTextField.frame = CGRectMake(290-completedTextFieldSize.width, 25, completedTextFieldSize.width+15, 20);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    currentIndexPath = indexPath;
    CGRect rectOfCellInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rectOfCellInSuperview = [tableView convertRect:rectOfCellInTableView toView:[tableView superview]];
    
    
    NSLog(@"%f %f",rectOfCellInSuperview.origin.x,rectOfCellInSuperview.origin.y);
    
    //Not in category Mode
    if (!isCategoryMode) {
        if(indexPath.row <loanRowNumber) {
            currentLoan = [loanArray objectAtIndex:indexPath.row];
            
            //Create pop up 
            if (popup == nil) {
                if (currentLoan.l_finished == FALSE) {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];

                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        } else {
            currentDebt = [debtArray objectAtIndex:indexPath.row-loanRowNumber];
            
            //Create pop up
            if (popup == nil) {
                if (currentDebt.d_finished == FALSE) {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];
                
                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        }
    } else {
        //Category Mode
        if(indexPath.section == 0) {
            currentLoan = [loanArray objectAtIndex:indexPath.row];
            
            //Create pop up
            if (popup == nil) {
                if (currentLoan.l_finished == FALSE) {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];
                
                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        } else {
            currentDebt = [debtArray objectAtIndex:indexPath.row];
 
            //Create pop up
            if (popup == nil) {
                if (currentDebt.d_finished == FALSE) {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];
                
                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        }
    }

}

#pragma mark -----------------Popup-----------------
- (void)didTouchPopupView:(SNPopupView*)sender {
    //	DNSLogMethod
    //	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}

#pragma mark ----------NSNotification Center ------------

-(void) addLoan_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if(!isCategoryMode){
        loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDate:currentDate];
        loanRowNumber = [loanArray count];
        debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDate:currentDate];
        debtRowNumber = [debtArray count];
    } else {
        loanArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllLoanInWallet:delegate.currentWallet]];
        loanRowNumber = [loanArray count];
        debtArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllDebtInWallet:delegate.currentWallet]];
        debtRowNumber = [debtArray count];
    }
    
    [self reloadLoanHistory];
    
    [loandebtTableView reloadData];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
}

-(void) addDebt_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if (!isCategoryMode) {
        loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDate:currentDate];
        loanRowNumber = [loanArray count];
        debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDate:currentDate];
        debtRowNumber = [debtArray count];
    } else {
        loanArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllLoanInWallet:delegate.currentWallet]];
        loanRowNumber = [loanArray count];
        debtArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllDebtInWallet:delegate.currentWallet]];
        debtRowNumber = [debtArray count];
    }
    
    [self reloadDebtHistory];
    
    [loandebtTableView reloadData];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
}

-(void) addLoanDebtHistory_onSuccess : (NSNotification*) notification {
    
    [self reloadLoanDebtHistory];
    
    [loandebtTableView reloadData];
}

#pragma mark ---------------IBAction Delegate----------------------
- (IBAction)editButtonPressed:(id)sender {
    if (!isCategoryMode) {        
        if(currentIndexPath.row < loanRowNumber) {
            AddLoanViewController *addLoanView = [[AddLoanViewController alloc]init];
            addLoanView.kindOfView = @"Edit";
            addLoanView.currentLoan = currentLoan;
            [self.navigationController pushViewController:addLoanView animated:YES];
        } else {
            AddDebtViewController *addDebtView = [[AddDebtViewController alloc]init];
            addDebtView.kindOfView = @"Edit";
            addDebtView.currentDebt = currentDebt;
            [self.navigationController pushViewController:addDebtView animated:YES];
        }
    } else {
        if (currentIndexPath.section == 0) {
            AddLoanViewController *addLoanView = [[AddLoanViewController alloc]init];
            addLoanView.kindOfView = @"Edit";
            addLoanView.currentLoan = currentLoan;
            [self.navigationController pushViewController:addLoanView animated:YES];
        } else {
            AddDebtViewController *addDebtView = [[AddDebtViewController alloc]init];
            addDebtView.kindOfView = @"Edit";
            addDebtView.currentDebt = currentDebt;
            [self.navigationController pushViewController:addDebtView animated:YES];
        }
    }
    [popup dismissModal];
}

- (IBAction)deleteButtonPressed:(id)sender {
    
    if (!isCategoryMode) {
        if(currentIndexPath.row < loanRowNumber) {
            [DataBaseAccess deleteLoan:[loanArray objectAtIndex:currentIndexPath.row]];
            [loanArray removeObjectAtIndex:currentIndexPath.row];
            
        } else {
            [DataBaseAccess deleteDebt:[debtArray objectAtIndex:currentIndexPath.row -loanRowNumber]];
            [debtArray removeObjectAtIndex:currentIndexPath.row-loanRowNumber];
        }
    } else {
        if(currentIndexPath.section == 0) {
            [DataBaseAccess deleteLoan:[loanArray objectAtIndex:currentIndexPath.row]];
            [loanArray removeObjectAtIndex:currentIndexPath.row];
            
        } else {
            [DataBaseAccess deleteDebt:[debtArray objectAtIndex:currentIndexPath.row]];
            [debtArray removeObjectAtIndex:currentIndexPath.row];
        }
    }
    
    [popup dismissModal];
    [loandebtTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
}

- (IBAction)viewButtonPressed:(id)sender {
    
    if (!isCategoryMode) {
        if(currentIndexPath.row < loanRowNumber) {
            ViewLoanViewController *viewLoanViewController = [[ViewLoanViewController alloc]init];
            viewLoanViewController.currentLoan = currentLoan;
            [self.navigationController pushViewController:viewLoanViewController animated:YES];
        } else {
            ViewDebtViewController *viewDebtViewController = [[ViewDebtViewController alloc]init];
            viewDebtViewController.currentDebt = currentDebt;
            [self.navigationController pushViewController:viewDebtViewController animated:YES];
        }
    } else {
        if(currentIndexPath.section == 0) {
            ViewLoanViewController *viewLoanViewController = [[ViewLoanViewController alloc]init];
            viewLoanViewController.currentLoan = currentLoan;
            [self.navigationController pushViewController:viewLoanViewController animated:YES];
        } else {
            ViewDebtViewController *viewDebtViewController = [[ViewDebtViewController alloc]init];
            viewDebtViewController.currentDebt = currentDebt;
            [self.navigationController pushViewController:viewDebtViewController animated:YES];
        }
    }
    
    [popup dismissModal];
}

- (IBAction)payButtonPressed:(id)sender {
    payHistoryAlertView = [[PayHistoryAlertView alloc]initWithNibName:@"PayHistoryAlertView" bundle:nil];
    
    if (!isCategoryMode) {
        if(currentIndexPath.row < loanRowNumber) {
            payHistoryAlertView.payType = 1;
            payHistoryAlertView.currentLoan = currentLoan;
        } else {
            payHistoryAlertView.payType = 2;
            payHistoryAlertView.currentDebt = currentDebt;
        }
    } else {
        if(currentIndexPath.section == 0) {
            payHistoryAlertView.payType = 1;
            payHistoryAlertView.currentLoan = currentLoan;
            [payHistoryAlertView.addButton setTitle:@"Add to Loan History" forState:UIControlStateNormal];
        } else {
            payHistoryAlertView.payType = 2;
            payHistoryAlertView.currentDebt = currentDebt;
            [payHistoryAlertView.addButton setTitle:@"Add to Debt History" forState:UIControlStateNormal];
        }
    }
    payHistoryAlertView.view.frame = CGRectMake(0, -40, 320, 460);
    [self.view addSubview:payHistoryAlertView.view];
    NSLog(@"%@", [self.view subviews]);
    [popup dismissModal];
}

#pragma mark -------------------Reload Data-------------------
-(void) reloadCustomDateTable {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDateFrom:startDate andDateTo:endDate];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDateFrom:startDate andDateTo:endDate];
    debtRowNumber = [debtArray count];
    
    [self reloadLoanDebtHistory];
    
    [loandebtTableView reloadData];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
}

-(void) reloadDailyTable {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDate:currentDate];
    loanRowNumber = [loanArray count];
    
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDate:currentDate];
    debtRowNumber = [debtArray count];
    
    [self reloadLoanDebtHistory];
    
    [loandebtTableView reloadData];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
}

-(void) reloadTableByCategory {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllLoanInWallet:delegate.currentWallet]];
    loanRowNumber = [loanArray count];
    
    debtArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllDebtInWallet:delegate.currentWallet]];
    debtRowNumber = [debtArray count];
    
    [self reloadLoanDebtHistory];
    
    [loandebtTableView reloadData];
    
    loanSum = 0;
    debtSum = 0;
    for(Loan *loan in loanArray) {
        loanSum += loan.l_amount.doubleValue;
    }
    for(Debt *debt in debtArray) {
        debtSum += debt.d_amount.doubleValue;
    }
    
    loanTotal.text = [NSString stringWithFormat:@"%f",loanSum];
    debtTotal.text = [NSString stringWithFormat:@"%f",debtSum];
}

-(void)reloadLoanDebtHistory {
    
    [self reloadLoanHistory];
    [self reloadDebtHistory];
}

-(void)reloadLoanHistory {
    //Get Loan History
    [loanCompletedArray removeAllObjects];
    for (Loan *tempLoan in loanArray) {
        double loanCompleted = 0;
        NSArray *tempLoanHistoryArray = [DataBaseAccess getAllLoanHistoryInLoan:tempLoan];
        if ([tempLoanHistoryArray count] > 0) {
            for (LoanHistory *loanHistory in tempLoanHistoryArray) {
                loanCompleted += [loanHistory.lh_amount doubleValue];
            }
            [loanCompletedArray addObject:[NSNumber numberWithDouble:loanCompleted]];
        } else {
            [loanCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
        
    }
}

-(void)reloadDebtHistory {
    //Get Debt History
    [debtCompletedArray removeAllObjects];
    for (Debt *tempDebt in debtArray) {
        double debtCompleted = 0;
        NSArray *tempDebtHistoryArray = [DataBaseAccess getAllDebtHistoryInDebt:tempDebt];
        if ([tempDebtHistoryArray count] > 0) {
            for (DebtHistory *debtHistory in tempDebtHistoryArray) {
                debtCompleted += [debtHistory.dh_amount doubleValue];
            }
            [debtCompletedArray addObject:[NSNumber numberWithDouble:debtCompleted]];
        } else {
            [debtCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
    }
}

@end
